package org.example.io.handler.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import org.apache.commons.lang3.StringUtils;
import org.example.io.protocol.packet.CreateGroupRequestPacket;
import org.example.io.protocol.packet.CreateGroupResponsePacket;
import org.example.io.session.SessionUtil;
import org.example.io.util.LogUtil;

import java.util.List;

public class CreateGroupRequestPacketHandler extends SimpleChannelInboundHandler<CreateGroupRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CreateGroupRequestPacket msg) throws Exception {
        StringBuffer sb = new StringBuffer("群创建成功，群里面有【");

        // 往每个channel发送消息
        ChannelGroup channelGroup = new DefaultChannelGroup(ctx.executor());
        List<String> userList = msg.getUserIds();
        for (int i = 0; i < userList.size(); i++) {
            Channel channel = SessionUtil.getChannel(userList.get(i));
            channelGroup.add(channel);
        }

        CreateGroupResponsePacket packet = new CreateGroupResponsePacket();
        packet.setGroupName(msg.getGroupName());
        packet.setUserIds(userList);
        channelGroup.writeAndFlush(packet);

        sb.append(StringUtils.join(userList, ",") + "】");
        LogUtil.info(sb.toString());
    }
}
